﻿/*
   Created 2009 December 6, Randall Maas
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/


using System;
using System . Collections . Generic;
using System . Windows. Forms; 
using System . Runtime . InteropServices;
//http://msdn.microsoft.com/en-us/magazine/cc301631.aspx

partial class DirectShowGraph : IDisposable
{
   /// <summary>
   /// The base filter of the device, used to access most of its features
   /// </summary>
   internal IGraphBuilder Graph;

   internal ICaptureGraphBuilder2 Graph2;

   /// <summary>
   /// The COM Guid of the FilterGraph class
   /// </summary>
   readonly static Guid CLSID_FilterGraph   = new Guid("e436ebb3-524f-11ce-9f53-0020af0ba770");


   /// <summary>
   /// The COM Guid of the CaptureGraphBuilder2 used to most of the work in building a graph
   /// </summary>
   readonly static Guid CLSID_CaptureGraphBuilder2   = new Guid("BF87B6E1-8C27-11d0-B3F0-00AA003761C5");

   internal DirectShowGraph()
   {
      Graph = (IGraphBuilder) COM . CreateInstanceFromType(CLSID_FilterGraph);
      Graph2 = (ICaptureGraphBuilder2) COM . CreateInstanceFromType(CLSID_CaptureGraphBuilder2);
      Graph2 . SetFiltergraph(Graph);
   }

   ~DirectShowGraph()
   {
      Dispose();
   }

   public void Dispose()
   {
      GC . SuppressFinalize(this);
//      if (0 <= Token)
//        Unpublish();
      Marshal . ReleaseComObject(Graph2);
      Marshal . ReleaseComObject(Graph);
   }

   /// <summary>
   /// The current stack of output video pins
   /// </summary>
   List<IPin> VideoOuts = new List<IPin> ();
   List<IPin> AudioOuts = new List<IPin> ();

   public bool Add(DirectShowNode N, string Name, AMMediaType Media)
   {
      _LastError = Graph . AddFilter(N . Filter, Name);

      int NumInPins=0, NumInPinsConnected=0; 
      // Hook up each of the pins
      foreach (IPin Pin in N.InPins())
      {
         IPin PinOut;
         NumInPins++;
         if (0 != VideoOuts. Count)
           {
              int Err = Graph2 . RenderStream(ref DirectShowNode . PIN_CATEGORY_CAPTURE,
                                             ref DirectShowNode . MEDIATYPE_Video,
                                             VideoOuts[VideoOuts . Count-1] ,
                                             null, N . Filter);

              if (0 == Err)
                {
                   NumInPinsConnected++;
                   VideoOuts . RemoveAt(VideoOuts . Count-1 );
                   continue;
                }

              if (null != (PinOut = Connect(VideoOuts[VideoOuts . Count-1], Pin, Media)))
                {
                   NumInPinsConnected++;
                   VideoOuts . RemoveAt(VideoOuts . Count-1 );
                   continue;
                }
           }

         if (0 != AudioOuts. Count)
           if (null != Connect(AudioOuts[AudioOuts . Count-1], Pin, null))//, Media))
             {
                NumInPinsConnected++;
                AudioOuts . RemoveAt(AudioOuts . Count-1 );
             }
      }

      // Next, figure out if it does something for the audio / video nodes
      List<IPin> RevPins = new List<IPin>(N . OutPins());
      RevPins . Reverse();
      foreach (IPin Pin in RevPins)
       foreach (AMMediaType MT in DirectShowNode . EnumerateMedia(Pin))
        if (MT . MajorType == DirectShowNode . MEDIATYPE_Audio)
          {
             AudioOuts . Add(Pin);
             break;
          }
        else if (MT . MajorType == DirectShowNode . MEDIATYPE_Video)
          {
             VideoOuts . Add(Pin);
//             if (null != Media)
//               Pin . SetMediaType(Media);
             break;
          }

      return NumInPins == NumInPinsConnected;
   }


   IPin Connect(IPin PinOut, IPin To, AMMediaType Media)
   {
      if (null == PinOut)
        return null;
      if (null != Media)
        if (0 == Graph . ConnectDirect(PinOut, To, Media))
          return PinOut;

      if (0 == Graph . Connect(PinOut, To))
        return PinOut;
      return null;
   }


   /// <summary>
   /// True if the render pin has been set
   /// </summary>
   bool RenderPinSet;

   void RenderPin()
   {
      //if (RenderPinSet)
      //  return ;

      // The Grabber to do video out of the graph
      IGraphBuilder Video = (IGraphBuilder ) Graph;

      // Go thru the output video pins and find one that we can render
      for (int I = VideoOuts . Count -1; I >= 0; I--)
      {
         IPin Pin = VideoOuts[I];
         foreach (AMMediaType MT in DirectShowNode . EnumerateMedia(Pin))
          if (  MT . MajorType == DirectShowNode . MEDIATYPE_Video
             && 0 == Video . Render(Pin))
            {
               VideoOuts . RemoveAt(I);
               RenderPinSet=true;
               return;
            }
      }
   }

   /// <summary>
   /// Renders the specified
   /// </summary>
   /// <param name="Pin"></param>
   internal void Render(IPin Pin)
   {
      Graph . Render(Pin);
   }

/*
   void Renderr()
   {
      Graph . RenderFile(NAme 
   }
*/
}

